<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('姓名')" prop="dsName">
            <el-input v-model="form.dsName" :placeholder="$t('姓名')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('性别')" prop="gender">
            <dictSelect v-model="form.gender" :clearable="true" dictionary="sys_user_sex" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('身份证')" prop="idNumber">
            <el-input v-model="form.idNumber" :placeholder="$t('身份证')" show-word-limit maxlength="18" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('手机号')" prop="phone">
            <el-input v-model="form.phone" :placeholder="$t('手机号')" show-word-limit maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计退休日期')" prop="estimatedRetirementDate">
            <el-date-picker
              v-model="form.estimatedRetirementDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              :placeholder="$t('预计退休日期')"
              @change="handleDateChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('距离退休时间')">
            <el-input v-model="form.timeToRetirement" :placeholder="$t('距离退休时间')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('个人简历')" prop="resumeId">
            <!-- accept=".pdf,.docx,.doc" -->
            <el-upload
              class="upload-demo"
              drag
              action
              :auto-upload="false"
              multiple
              :before-upload="beforeUpload"
              :on-exceed="handleFileExceed"
              :file-list="uploadResume"
              :on-change="onChange"
              :on-remove="onRemove"
              show-file-list
              :limit="1"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>
                <div class="el-upload__tip">支持 WORD , PDF</div>
                <div class="el-upload__tip">文件大小应在5KB~50MB之间</div>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('任职情况') }}</span>
      </div>
      <el-table :data="bodList" class="nowrapTable formTable" border>
        <el-table-column :label="$t('企业名称')" align="center" prop="companyName" />
        <el-table-column :label="$t('职务')" align="center" prop="dutyLabel" />
        <el-table-column :label="$t('状态')" align="center" prop="incumbentTypeName" />
        <el-table-column :label="$t('任职开始时间')" align="center" prop="startDate">
          <template slot-scope="scope">
            {{ parseTime(scope.row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('任职结束时间')" align="center" prop="endDate">
          <template slot-scope="scope">
            {{ parseTime(scope.row.endDate) }}
          </template>
        </el-table-column>
        <!-- <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="140">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-view" @click="viewHandler(scope.row)">{{ $t("查看") }}</el-button>
          </template>
        </el-table-column> -->
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="system:manager" />
    </div>
  </div>
</template>

<script>
import {
  saveDsSeniorManagerData,
  getDsSeniorManager
} from '@/api/fund/ds/dsSeniorManager'
export default {
  props: {
    isShowList: {
      type: Boolean,
      default: true
    }
  },
  data() {
    var checkIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('身份证号码不能为空'))
      }
      // 这里使用了一个简单的正则表达式进行校验，实际项目中可能需要更复杂的校验逻辑
      const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}([0-9]|X|x)$/
      if (!idCardRegex.test(value)) {
        callback(new Error('身份证号码格式不正确'))
      } else {
        callback()
      }
    }
    return {
      pickerOptions: {
        disabledDate(time) {
          const today = new Date()
          const currentTime = today.getTime()
          const dateTime = time.getTime()
          return dateTime < currentTime
        }
      },
      // 简历
      uploadResume: [],
      // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      bodList: [],
      // 表单校验
      rules: {
        dsName: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        }],
        gender: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        }],
        idNumber: [{
          validator: checkIdCard,
          trigger: 'blur',
          required: true
        }],
        phone: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
      ],
        estimatedRetirementDate: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        }]
      }
    }
  },
  created() {},
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getDsSeniorManager(data.id).then(response => {
          this.form = response.data
          this.bodList = response.data.bodList
          this.handleDateChange()
          this.uploadResume = []
          this.uploadResume.push(response.data.fileBase)
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.uploadResume = []
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        orgId: this.$route.query.id,
        dsName: undefined,
        gender: undefined,
        idNumber: undefined,
        phone: undefined,
        estimatedRetirementDate: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.uploadResume.length === 0) {
            this.$message({
              message: '请先上传文件',
              type: 'warning'
            })
            return
          }
          this.loading = true
          const formData = new FormData()
          // 标准文档
          this.uploadResume.forEach((item) => {
            if (item.raw) {
              formData.append('resumeFile', item.raw)
            }
          })
          this.loading = true
          formData.append('dsSeniorManager', JSON.stringify(this.form))
          saveDsSeniorManagerData(formData).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              if (this.$parent.$parent.assignSeniorManagerHandler) {
                this.$parent.$parent.assignSeniorManagerHandler(response.data)
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
              } else {
                this.closeForm()
              }
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handleDateChange() {
      var targetDate = new Date(this.form.estimatedRetirementDate)
      var timeDifference = this.calculateTimeDifference(targetDate)
      this.form.timeToRetirement = timeDifference
      this.$forceUpdate()
    },
    viewHandler(row) {
      console.log(row)
    },
    calculateTimeDifference(targetDate) {
      // 获取当前日期
      var currentDate = new Date()
      // 计算日期差异
      var timeDifference = targetDate - currentDate
      var millisecondsInYear = 1000 * 60 * 60 * 24 * 365
      var years = Math.floor(timeDifference / millisecondsInYear)
      var remainingMilliseconds = timeDifference % millisecondsInYear
      var months = Math.floor(remainingMilliseconds / (1000 * 60 * 60 * 24 * 30))
      var result = ''
      if (years === 0) {
        result = (months + 1) + '个月'
      } else {
        result = years + '年' + (months + 1) + '个月'
      }
      return result
    },
    beforeUpload(file) {
      const isLt5K = file.raw.size < this.minSize
      const isGt50M = file.raw.size > this.maxSize
      if (isLt5K || isGt50M) {
        // this.$message.error(`文件大小应在5KB~50MB之间`)
        return false
      }
      return true
    },
    handleFileExceed() {
      this.msgError(this.$t('仅限可上传 1 个文件'))
    },
    onChange(file, fileList) {
      for (let i = fileList.length - 1; i >= 0; i--) {
        const file = fileList[i]
        const isLt5K = file.raw.size < this.minSize
        const isGt50M = file.raw.size > this.maxSize
        if (isLt5K || isGt50M) {
          fileList.splice(i, 1)
          const message = isLt5K ? '文件过小' : '文件过大'
          this.$message.warning(`${file.name} ${message}`)
        }
      }
      this.uploadResume = fileList
    },
    onRemove(file, fileList) {
      this.uploadResume = fileList
    }
  }
}
</script>
